<template>
  <div id="Login">
    <div class="login">
      <div class="loginTitle">汇鑫种养殖</div>
      <el-form size="mini" :model="ruleForm" :rules="loginRules" ref="ruleForm" class="demo-ruleForm">
        <el-form-item prop="userName">
          <el-input type="text" v-model="ruleForm.userName" placeholder="账号"></el-input>
        </el-form-item>
        <el-form-item prop="passWord">
          <el-input show-password v-model="ruleForm.passWord" placeholder="密码"></el-input>
        </el-form-item>
        <!-- <el-form-item prop="desc">
          <el-input type="text" v-model="ruleForm.desc" placeholder="验证码"></el-input>
        </el-form-item> -->
        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%;"
            @click.native.prevent="handleLogin"
          >
          <span>登 录</span>
            <!-- <span v-if="!loading">登 录</span> -->
            <!-- <span v-else>登 录 中...</span> -->
          </el-button>
          <!-- <div style="float: right;" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div> -->
          <div
            style="text-align: center; color: #2211da; cursor:pointer;"
            @click="forgetPassword">忘记密码?</div>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog
      title="修改密码"
      :visible.sync="resetPassword"
      :close-on-press-escape="true"
      :close-on-click-modal="false"
      @close="closeDialog">
      <el-form ref="refWord" :model="formWord" :rules="formWordRule" label-width="100px">
        <el-form-item label="用户名" prop="userAll">
          <el-input v-model="formWord.userAll"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="formWord.phone">
            <el-button slot="append" @click="getCode">{{ !downTime ? '获取验证码' : `${timedelet}秒后重新发送`}}</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="verCode">
          <el-input v-model="formWord.verCode"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="formWord.newPassword"></el-input>
        </el-form-item>
        <el-form-item label="重复新密码" prop="repeatPassword">
          <el-input v-model="formWord.repeatPassword"></el-input>
        </el-form-item>
        <div style="width: 100%; text-align: center;">
          <el-button type="primary" @click="commitPostion">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
    <div class="theRecord" @click="goHref">
      备案号：蜀ICP备2024080598号-1
    </div>
  </div>
</template>

<script>
import { login, getRouters, PwdCode, updatePwd } from '@/api/user'
import { setToken } from '@/until/token'
import { companyInfo } from '@/api/Company'
export default {
  name: 'LivestocksystemIndex',
  watch: {
    downTime (newVal, oldVal) {
      if (newVal) {
        const overTime = setInterval(() => {
          this.timedelet--
          if (this.timedelet === 0) {
            this.downTime = false
            clearInterval(overTime)
            this.timedelet = 5
          }
        }, 1000)
      }
    }
  },

  data () {
    const that = this
    return {
      downTime: false,
      timedelet: 5,
      resetPassword: false,
      loading: false,
      ruleForm: {
        userName: '',
        passWord: '',
        rememberMe: false
      },
      formWord: {
        userAll: '',
        phone: '',
        verCode: '',
        newPassword: '',
        repeatPassword: ''
      },
      formWordRule: {
        userAll: [
          { required: true, trigger: 'blur', message: '请输入用户名' }
        ],
        phone: [
          { required: true, trigger: 'blur', message: '请输入手机号' },
          {
            validator (_, value, callback) {
              const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
              if (!regTel.test(value)) {
                callback(new Error('手机号不符合规则'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        verCode: [
          { required: true, trigger: 'blur', message: '请输入验证码' }
        ],
        newPassword: [
          { required: true, trigger: 'blur', message: '请输入密码' }
        ],
        repeatPassword: [
          { required: true, trigger: 'blur', message: '请重复密码' },
          {
            validator (_, value, callback) {
              const tempNum = that.formWord.newPassword
              if (value !== tempNum) {
                callback(new Error('两次密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      loginRules: {
        userName: [
          { required: true, trigger: 'blur', message: '请输入您的账号' }
        ],
        passWord: [
          { required: true, trigger: 'blur', message: '请输入您的密码' }
        ]
        // code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      }
    }
  },

  mounted () {
    window.addEventListener('keydown', this.keyDown)
  },
  destroyed () {
    window.removeEventListener('keydown', this.keyDown, false)
  },
  methods: {
    goHref () {
      location.href = 'https://beian.miit.gov.cn/#/Integrated/index'
    },
    // 监听回车键执行事件
    keyDown (e) {
      // 回车则执行登录方法 enter键的ASCII是13
      if (e.keyCode === 13) {
        this.handleLogin() // 需要执行的方法方法
      }
    },
    forgetPassword () {
      this.resetPassword = true
    },
    closeDialog () {
      this.resetPassword = false
    },
    commitPostion () {
      this.$refs.refWord.validate(valid => {
        if (valid) {
          const obj = {
            passWord: this.formWord.newPassword,
            userName: this.formWord.userAll,
            validCode: this.formWord.verCode
          }
          updatePwd(obj).then(res => {
            if (res.code === '200') {
              this.resetPassword = false
              this.$message({
                message: res.message,
                type: 'success'
              })
            } else {
              this.$message({
                message: res.message,
                type: 'warning'
              })
            }
          })
        }
      })
    },
    getCode () {
      const regTel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (this.formWord.phone !== '' && regTel.test(this.formWord.phone)) {
        this.downTime = true
        PwdCode(this.formWord.phone, this.formWord.userAll).then(res => {
          if (res.code === '200') {
            this.$message({
              message: res.message,
              type: 'success'
            })
          }
        })
      }
    },
    handleLogin () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.loading = true
          login(this.ruleForm.userName, this.ruleForm.passWord).then(res => {
            if (res.code === '200') {
              setToken(res.data.token)
              sessionStorage.setItem('userLoginId', res.data.sysUser.id)
              getRouters().then(res => {
                if (res.code === '200') {
                  this.loading = true
                  const result = this.routeDa(res.data)
                  const routerList = JSON.stringify(result)
                  sessionStorage.setItem('routerList', routerList)
                  this.loading = false
                  companyInfo().then(res => {
                    if (res.code === '200') {
                      sessionStorage.setItem('companyName', res.data.name)
                      this.$router.push({ path: '/panelIndex' })
                    } else {
                      this.$message({
                        message: res.message,
                        type: 'warning'
                      })
                    }
                  })
                } else {
                  this.$message({
                    message: res.message,
                    type: 'warning'
                  })
                }
              }).catch(err => {
                return err
              })
            } else {
              this.loading = false
              this.$message({
                message: res.message,
                type: 'warning'
              })
            }
          }).catch(err => {
            return err
          })
        }
      })
    },
    routeDa (asyncRouterMap) {
      const routeNull = []
      asyncRouterMap.forEach(route => {
        const routeChid = {}
        routeChid.path = '/' + route.url
        routeChid.icon = route.icon
        routeChid.perms = route.perms
        routeChid.name = route.name
        routeChid.id = route.id
        routeNull.push(routeChid)
        if (route.children === undefined) {
          return routeNull
        } else if (route.children) {
          route.children = this.filterChildren(route.children)
          routeChid.children = route.children
        }
      })
      return routeNull
    },
    filterChildren (childrenMap) {
      const childrenArr = []
      childrenMap.forEach((el, index) => {
        const childrenObj = {}
        childrenObj.path = el.url
        childrenObj.name = el.name
        childrenObj.perms = el.perms
        childrenObj.id = el.id
        childrenArr.push(childrenObj)
        if (el.children === undefined) {
          return childrenArr
        } else if (el.children !== undefined && el.children.length > 0) {
          childrenObj.children = this.setButton(el.children)
        }
      })
      return childrenArr
    },
    setButton (buttonChild) {
      const buttonArr = []
      buttonChild.forEach((el, index) => {
        const bottonObj = {}
        bottonObj.path = el.url
        bottonObj.name = el.name
        bottonObj.perms = el.perms
        bottonObj.id = el.id
        buttonArr.push(bottonObj)
      })
      return buttonArr
    }
  }
}
</script>
<style lang="scss">
#Login {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #c7e9fb, #a6defa, #80d4f9, #5bc9f8, #35bef7);
  position: absolute;
  top: 0;
  right: 0;
  .login {
    padding: 10px 20px;
    width: 20%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    height: auto;
    background-color: #fff;
    .loginTitle {
      text-align: center;
      font-size: 16px;
      font-weight: 600;
      margin: 10px 0;
    }
  }
  .theRecord {
    font-size: 12px;
    cursor:pointer;
    width: 400px;
    text-align: center;
    position: absolute;
    bottom: 10px;
    right: 50%;
    transform: translate(200px);
    color: #0000ed;
  }
}
</style>
